<template>
	<gui-page ref="guiPage" :customHeader="true">
		<!-- 导航 -->
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :leftType="'1'" @clickLeftBack="clickLeftBack"
				:title="$t('barcodeChange.returnFGMaterials')" :rightText="$t('distributedEnter.scanRecord')" @clickRight="clickRight"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class=" page-auto" :style="'height: calc(100vh - ' + navHeight + 'px);'">
				<view class="gui-bg-white gui-padding-x distributed-head">
					<!--仓库-->
					<view class="custom-card-itemTwo cradItem" style="padding: 20rpx 0;">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('distributedOut.warehouse')
						}}：</text>
						<comboGrid requestUrl="/wms/wmsWarehouse/getIsUsePageSetPDA" v-model="data.warehouseCode"
							:modelValue="data.warehouseCode" :requestParam="data.warehouseParam"
							inputKey="warehouseName" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('pageTranslation.plsInputFilter')" :column="data.columnHome.column"
							bindValue="warehouseCode" @setClick="handelGetClick" :rm="false" :FYR="true"></comboGrid>
					</view>
					<!--库位-->
					<!--  v-if="data.locationWarehouseId.length"  -->
					<view  v-if="data.locationWarehouseId.length" class="custom-card-itemTwo cradItem">
						<text class="item-info-title"><text class="required-color">*</text>{{
							$t('distributedOut.location')
						}}：</text>
						<!-- 有容量的库位 -->
						<comboGrid requestUrl="/wms/wmsLocation/getIsUsePageSetByWarehousePDA"
							v-model="data.locationCode" :calculate="data.calculate" :requestParam="data.requestParam"
							inputKey="locationCode" :placeholder="$t('distributedEnter.placeholderTextChoose')"
							:gridPlaceholder="$t('pageTranslation.plsInputFilter')" :column="data.columnLocation.column"
							bindValue="locationCode" @setClick="getLocationClick"></comboGrid>
					</view>
					<!-- 扫描条码部分 -->
					<view class="custom-card-itemTwo cradItem" style="padding: 0 0 20rpx;">
						<text class="item-info-title"><text
								class="required-color">*</text>{{ $t('distributedEnter.barcodeScan') }}：</text>
						<view class="custom-card-scan" style="margin-top: 20rpx;">
							<uni-easyinput class="uni-mt-5" suffixIcon="scan" v-model="data.scanValue"
								:placeholder="$t('stockManage.pleaseScanCode')" @confirm="confirm"
								@iconClick="iconClick">
							</uni-easyinput>
						</view>
					</view>
				</view>
				<!-- 卡片模块 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll element-auto">
					<view style="height: 15rpx"></view>
					<view v-if="data.barcodeInfo" class="card-boxCustom">
						<view class="card-body">
							<view class="custom-card-title">
								<text class="title-line"></text>{{ $t('pageTranslation.plsScanBarcodeInfo') }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCoded') }}：</text>{{ data.barcodeInfo.barcode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialCode') }}：</text>{{ data.barcodeInfo.materialCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedEnter.materialName') }}：</text>{{ data.barcodeInfo.materialName }}
							</view>
							<view class="custom-card-itemOne">
								<text
									class="body-item-title">{{ $t('distributedEnter.materialSpec') }}：</text>{{ data.barcodeInfo.materialSpec }}
							</view>
							<view class="custom-card-itemOne">
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.uom') }}：</text>{{ data.barcodeInfo.unit }}
								</view>
								<view class="card-item-50">
									<text class="body-item-title">{{ $t('distributedEnter.qty') }}：</text>{{ data.barcodeInfo.currentQty }}
								</view>
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.warehouse') }}：</text>{{ data.barcodeInfo.warehouseCode }}
							</view>
							<view class="custom-card-itemOne">
								<text class="body-item-title">{{ $t('distributedOut.location') }}：</text>{{ data.barcodeInfo.locationCode }}
							</view>
						</view>
					</view>
				</scroll-view>
				<!-- 底部确定按钮 -->
				<view class="page-bottom-box bottom-postion">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="handelSubmit">{{ $t('calendar.submit') }}</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import {ref,reactive,onMounted,computed,watch} from 'vue';
import {navigate,navigateBack} from '@/utils/routerSkip.js';
import { getDataDictionaryFn, pitchOnFn } from '@/utils/index.js'
import storageBin from '@/components/storageBin.vue';
import comboGrid from "@/components/comboGrid";
import {useStore} from "vuex";
import {onShow} from '@dcloudio/uni-app';
import {basPdaOperationLogFn} from '@/utils/index.js';
import pdaScan from '@/hooks/pdaScan.js'
import spChooseBox from '@/components/spChooseBox';
import chooseSelect from '@/components/chooseSelect';
import { onBackPress } from '@dcloudio/uni-app';
import { BIGBARCODER_PRINT } from '@/constant/index.js'
import superweiCombox from '@/components/superweiCombox';
import {selectWmsBarcodeInfoWms, productReturnSubmit,getIsUsePageSetPDA} from '@/api/api.js'
//JS国际化引入
import {useI18n} from 'vue-i18n';
const {t} = useI18n();

const {scan} = pdaScan()
//注册组件
components: {
	storageBin,
		comboGrid,
		spChooseBox,
		chooseSelect,
		superweiCombox
}
let store = useStore();
let data = reactive({
	scanValue: '',//扫描的条码
	calculate: false, // 是否是容量的数据
	warehouseName: "", //仓库名称
	warehouseId: '',
	warehouseCode: '',
	barcodeInfo: null, //存储后端返回的数据,card的信息
	returnTypes: [], //退料原因数组
	returnType: '', //退料原因code
	returnTypeName: '',
	stockReturnTypes: [], //退库原因数组
	stockReturnType: '', //退库原因code
	stockReturnTypeName: '',
	scanList: [],// 扫描的条码信息
	// 仓库
	warehouseParam: {
		warehouseName: "", //仓库
	},
	locationName: "", //库位名称
	locationId: '',
	locationWarehouseId: '', //设置的默认仓库
	locationCode: '',
	peportmentList: [],//领料人数组
	deportmentCode: '', //领料部code
	department: '', //领料部门
	// 库位
	requestParam: {
		warehouseId: "", // 设置的默认仓库
		locationCode: "",
		locationTypeName: 'WarehouseLocation'
	},

	//仓库代码下面的筛选
	columnHome: {
		column: [{
			label: t('distributedOut.warehouse'),
			name: "warehouseCode",
		}]
	},
	columnLocation: {
		column: [{
			label: t('distributedOut.volumnStockName'),
			name: "locationCode",
		}]
	},
	columnRule: {
		column: [{
			label: t('pageTranslation.barcodeType'),
			name: "ruleCode",
		}]
	}
})

const navHeight = computed(() => {
	return store.state.navHeight
})

const getInitData = async () => {
	// 获取领料人数据
	data.peportmentList = await getDataDictionaryFn('Deportment')
	let tepSelect1 = pitchOnFn(data.peportmentList)
	if (tepSelect1.length == 0) return
}


onShow(async () => {
	//没有设置默认打印机则去提示设置默认打印机
	const defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (defaultValue == '') {
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText: t('pageTranslation.toSet'),
			success: function (res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/setting/printer'
					})
				} else if (res.cancel) {

				}
			}
		});
	}
	getReturnData()
	getStockReturnData()
	getInitData()
})


//扫描的条码信息
data.scanList = computed(() => {
	return store.state.productReturnList
})

//监听pda扫码
onMounted(() => {
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
})

const filter = async () => {
	// 查询目的仓库
	let locationCapacity = await getDataDictionaryFn('LocationCapacity')
	let bool = locationCapacity.some((item) => {
		return item.value == data.warehouseCode
	})
	if (bool) {
		data.calculate = true
		// maxCapacity
		data.columnLocation = {
			column: [{
				label: t('JsInternational.volumnStockName'),
				name: "locationCode",
			}, {
				label: t('pageTranslation.volumeOfLocation'),
				name: "lastInventory",
			}]
		}
	} else {
		data.calculate = false
		data.columnLocation = {
			column: [{
				label: t('JsInternational.volumnStockName'),
				name: "locationCode",
			}]
		}
	}
}
watch(() => data.warehouseCode, (newVal, oldVal) => {
	filter()
}, {
	immediate: true,
	deep: true
});

// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}

// 用户点击键盘上搜索
const confirm = () => {
	getCode(data.scanValue, 'keydown')
}

// 获取code，查询barcode信息
const getCode = (code, type) => {
	if (!data.warehouseCode) {
		uni.showToast({
			title: t('pageTranslation.plsChooseWarehous'),
			icon: 'error'
		})
		return;
	}

	if (!data.locationCode) {
		uni.showToast({
			title: t('pageTranslation.plsChooseLocatoinFirstly'),
			icon: 'error'
		})
		return;
	}
	//判断是否扫描过该条码
	var exist = data.scanList.filter(e => e.barcode == code);
	if (exist.length > 0) {
		uni.showToast({
			title: t('distributedOut.repeatScan'),
			icon: 'error'
		})
		return;
	}

	let parmes = {
		barcode: code,
		selectType: 'productReturn'
	}
	selectWmsBarcodeInfoWms(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品退库退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res)
		if (res.status == 200) {
			res.data.warehouseId = data.warehouseId
			res.data.warehouseCode = data.warehouseCode
			res.data.warehouseName = '精加工'
			res.data.locationId = data.locationId
			res.data.locationName = data.locationName
			res.data.locationCode = data.locationCode
			res.data.department = data.department
			res.data.deportmentCode = data.deportmentCode
			//添加到store
			store.commit('addProductReturnList', res.data)
			data.barcodeInfo = res.data

		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})
}
// 获取选中的仓库的id
const handelGetClick = (x) => {
	data.warehouseId = x.id ? x.id : '';
	data.warehouseName = x.warehouseName ? x.warehouseName : '';
	data.warehouseCode = x.warehouseCode ? x.warehouseCode : '';
	// if(!Object.keys(x).length) return
	data.requestParam.warehouseId = x.id ? x.id + '' : '';
	data.locationWarehouseId = x.id ? x.id + '' : '';
	data.locationName = ""; //仓库发生变化清空库位
	data.locationId = ''
	data.locationCode = ''
}

//库位选择之后赋值给变量
const getLocationClick = (x) => {
	data.locationId = x.id
	data.locationName = x.locationName;
	data.locationCode = x.locationCode;
}

//退料类型不选择
const noReturnselect = (e) => {
	uni.showToast({
		title: t('JsInternational.haveNo'),
		icon: "none"
	});
	return
}

//退料类型选择
const ReturnSelect = (e) => {
	data.returnTypeName = e.remark
	data.returnType = e.value
}

//退料类型数据
const getReturnData = async () => {
	data.returnTypes = await getDataDictionaryFn('ReturnType')
	let tepSelect1 = pitchOnFn(data.returnTypes)
	if (tepSelect1.length == 0) return
}


//退库类型不选择
const noStockReturnselect = (e) => {
	uni.showToast({
		title: t('JsInternational.haveNo'),
		icon: "none"
	});
	return
}

//退库类型选择
const StockReturnSelect = (e) => {
	data.stockReturnTypeName = e.text
	data.stockReturnType = e.value
}

//退库类型数据
const getStockReturnData = async () => {
	data.stockReturnTypes = await getDataDictionaryFn('StockReturnType')
	let tepSelect1 = pitchOnFn(data.stockReturnTypes)
	if (tepSelect1.length == 0) return
}

//提交
const handelSubmit = () => {
	if (!data.scanList.length) {
		uni.showToast({
			title: '请扫描条码',
			icon: 'error'
		})
		return
	}

	let parmes = { wmsBarcodes: [] }
	let barcodearr = ''
	data.scanList.forEach(e => {
		var obj = {
			warehouseCode: e.warehouseCode,
			locationCode: e.locationCode,
			returnType: e.returnType,
			productObject: e.materialCode,
			stockReturnType: e.stockReturnType,
			currentQty: e.currentQty,
			id: e.id,
			deptCode: e.deportmentCode
		}
		barcodearr += (e.barcode) + ",";
		parmes.wmsBarcodes.push(obj)
	})

	//提交数据
	productReturnSubmit(parmes).then(res => {
		console.log(res)
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '成品退货退料'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_COMMIT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//删除已提交的数据
			data.scanValue = ''
			data.barcodeInfo = null
			data.locationId = ''
			data.locationCode = ''
			data.locationName = ''
			data.warehouseCode = '',
				data.warehouseName = ''
			data.warehouseId = ''
			data.returnType = ''
			data.returnTypeName = ''
			data.stockReturnType = ''
			data.stockReturnTypeName = ''
			data.department = ''
			data.deportmentCode = ''
			uni.showToast({ title: t('smashRemoval.submitSuccessfully'), icon: "none" });
			store.commit('clearProductReturnList')
			setTimeout(function () {
				navigate({
					url: '/pages/finishedInventory/finishedInventoryPrint?barcode=' + barcodearr
				})
			}, 50);

		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	})

}


//扫描纪录
const clickRight = () => {
	navigate({
		url: '/pages/finishedInventory/finishedInventoryReturnRecord'
	})
}

//点击物理按键的返回
onBackPress((options) => {
	if (options.from == 'backbutton') {
		if (!data.scanwoodenList.length) {
			uni.navigateBack({
				delta: 1
			});
			return true
		}
		uni.showModal({
			title: t('smashRemoval.warmPrompt'),
			content: t('materials.unsubmittedDataIn'),
			success: function (res) {
				if (res.confirm) {
					//清除store 里面的数据
					store.commit("clearProductReturnList");
					uni.navigateBack({
						delta: 1
					});
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return true;
	}
})
//导航栏左侧返回
const clickLeftBack = () => {
	if (!data.scanList.length) {
		uni.navigateBack({
			delta: 1
		});
		return
	}
	uni.showModal({
		title: t('smashRemoval.warmPrompt'),
		content: t('materials.unsubmittedDataIn'),
		success: function (res) {
			if (res.confirm) {
				store.commit("clearProductReturnList")
				uni.navigateBack({
					delta: 1
				});
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	});
}
</script>

<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
	// height: 100vh;
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

@media (prefers-color-scheme: dark) {
	.custom-card-title {
		color: #fff !important;
	}
}

.cradItem {
	margin-bottom: 20rpx;
}
</style>